// src/store/trouble.js
import { defineStore } from 'pinia';

export const useTroubleStore = defineStore('trouble', {
  state: () => ({
    // 故障菜单项数据（支持三级结构）
    menuItems: [
      {
        id: "basic-principles",
        title: "发电机定子绕阻温度高报警（PTC145）",
        icon: "Document",
        children: [
          {
            id: "overload",
            title: "运行过载",
            icon: "Notebook",
            children: []
          },
          {
            id: "low-water-flow",
            title: "水流量偏低",
            icon: "DataAnalysis",
            children: [],
          },
          {
            id: "3d-explosion",
            title: "风路堵塞",
            icon: "View",
            children: [],
          },
          {
            id: "poor-contact",
            title: "PTC线路接触不良",
            icon: "Temperature",
            children: [],
          },
          {
            id: "ptc-damage",
            title: "PTC损坏",
            icon: "Warning",
            children: [],
          }
        ],
      },
    ],
    // 当前选中的故障项
    selectedTrouble: null,
    // 故障处理状态
    troubleStatus: {
      loading: false,
      error: null,
      lastUpdated: null
    }
  }),

  getters: {
    // 获取所有故障菜单
    getAllTroubles: (state) => state.menuItems,
    
    // 获取故障总数
    getTroubleCount: (state) => {
      let count = 0;
      state.menuItems.forEach(item => {
        count++;
        if (item.children) {
          count += item.children.length;
          item.children.forEach(child => {
            if (child.children) {
              count += child.children.length;
            }
          });
        }
      });
      return count;
    },
    
    // 根据ID获取故障项
    getTroubleById: (state) => (id) => {
      let result = null;
      
      const findTrouble = (items) => {
        for (const item of items) {
          if (item.id === id) {
            result = item;
            return true;
          }
          if (item.children && item.children.length > 0) {
            if (findTrouble(item.children)) {
              return true;
            }
          }
        }
        return false;
      };
      
      findTrouble(state.menuItems);
      return result;
    },
    
    // 获取当前选中的故障
    getSelectedTrouble: (state) => state.selectedTrouble,
  },

  actions: {
    // 设置加载状态
    setLoading(loading) {
      this.troubleStatus.loading = loading;
    },
    
    // 设置错误信息
    setError(error) {
      this.troubleStatus.error = error;
    },
    
    // 清除错误信息
    clearError() {
      this.troubleStatus.error = null;
    },
    
    // 更新最后更新时间
    updateLastUpdated() {
      this.troubleStatus.lastUpdated = new Date();
    },
    
    // 设置选中的故障项
    selectTrouble(trouble) {
      // 单选逻辑：如果点击的是已选中的项，则取消选中；否则选中该项
      if (this.selectedTrouble && this.selectedTrouble.id === trouble.id) {
        this.selectedTrouble = null;
      } else {
        this.selectedTrouble = trouble;
      }
    },
    
    // 取消选中
    unselectTrouble() {
      this.selectedTrouble = null;
    },
    
    // 检查故障项是否被选中
    isTroubleSelected(troubleId) {
      return this.selectedTrouble && this.selectedTrouble.id === troubleId;
    },
    
    // 添加新的故障项
    addTroubleItem(item, parentId = null) {
      try {
        this.setLoading(true);
        this.clearError();
        
        // 生成唯一ID
        const newItem = {
          id: item.id || `trouble-${Date.now()}`,
          ...item,
          children: item.children || []
        };
        
        if (!parentId) {
          // 添加为顶级故障
          this.menuItems.push(newItem);
        } else {
          // 查找父级并添加为子项
          const findAndAdd = (items) => {
            for (let i = 0; i < items.length; i++) {
              if (items[i].id === parentId) {
                if (!items[i].children) {
                  items[i].children = [];
                }
                items[i].children.push(newItem);
                return true;
              }
              if (items[i].children && items[i].children.length > 0) {
                if (findAndAdd(items[i].children)) {
                  return true;
                }
              }
            }
            return false;
          };
          
          if (!findAndAdd(this.menuItems)) {
            throw new Error(`未找到ID为${parentId}的故障项`);
          }
        }
        
        this.updateLastUpdated();
        return newItem;
      } catch (error) {
        this.setError(error.message);
        throw error;
      } finally {
        this.setLoading(false);
      }
    },
    
    // 更新故障项
    updateTroubleItem(id, updates) {
      try {
        this.setLoading(true);
        this.clearError();
        
        const updateItem = (items) => {
          for (let i = 0; i < items.length; i++) {
            if (items[i].id === id) {
              items[i] = {
                ...items[i],
                ...updates
              };
              return true;
            }
            if (items[i].children && items[i].children.length > 0) {
              if (updateItem(items[i].children)) {
                return true;
              }
            }
          }
          return false;
        };
        
        if (!updateItem(this.menuItems)) {
          throw new Error(`未找到ID为${id}的故障项`);
        }
        
        this.updateLastUpdated();
        return true;
      } catch (error) {
        this.setError(error.message);
        throw error;
      } finally {
        this.setLoading(false);
      }
    },
    
    // 删除故障项
    deleteTroubleItem(id) {
      try {
        this.setLoading(true);
        this.clearError();
        
        const deleteItem = (items) => {
          for (let i = 0; i < items.length; i++) {
            if (items[i].id === id) {
              items.splice(i, 1);
              return true;
            }
            if (items[i].children && items[i].children.length > 0) {
              if (deleteItem(items[i].children)) {
                return true;
              }
            }
          }
          return false;
        };
        
        if (!deleteItem(this.menuItems)) {
          throw new Error(`未找到ID为${id}的故障项`);
        }
        
        // 如果删除的是当前选中的项，取消选中
        if (this.selectedTrouble && this.selectedTrouble.id === id) {
          this.unselectTrouble();
        }
        
        this.updateLastUpdated();
        return true;
      } catch (error) {
        this.setError(error.message);
        throw error;
      } finally {
        this.setLoading(false);
      }
    },
    
    // 重置故障数据
    resetTroubles() {
      this.menuItems = [];
      this.selectedTrouble = null;
      this.troubleStatus = {
        loading: false,
        error: null,
        lastUpdated: null
      };
    },
    
    // 批量更新故障数据
    setTroubleItems(items) {
      try {
        this.setLoading(true);
        this.clearError();
        
        // 验证数据格式
        if (!Array.isArray(items)) {
          throw new Error('故障数据必须是数组格式');
        }
        
        this.menuItems = items;
        this.updateLastUpdated();
        return true;
      } catch (error) {
        this.setError(error.message);
        throw error;
      } finally {
        this.setLoading(false);
      }
    }
  }
});
